<template>
	<view id = "main">

		<u-toast ref="uToast"></u-toast>
		<u-toast ref="uToastSuccess"></u-toast>

		<view class="header">
			<view class="main_title">
				当前任务：{{info.surveyName}}
			</view>
			<view class="vice_title">
				副标题：{{curLabelName}}
			</view>

			<view class='header_footer'>
				<text>(tips：先保存，后提交)</text>
				<u-button size='mini' class='top-Button' hover-class='none'  @click='this.show2 = true'>提交</u-button>
				<u-button size='mini' class='top-Button' hover-class='none'  @click='this.show3 = true'>暂存</u-button>
			</view>
		</view>

		<view class='productNav'>
		  <!-- 左侧 -->
		  <!-- <view class='left'>
			  <view v-for="(item, index) of labelList" :key="index">
		         <view :class="active == index?'selected':'normal'" :id="index" @click='switchNav'>{{item.label}}</view>
			  </view>
		  </view> -->

		  <!-- 右侧 -->
		  <view class='right'>
		    <view class='type'>

				<block v-for="(item, index) of labelList" :key="index">
					<view v-show="index == currentTab">
						<view class='container' v-if="qList.length !== 0">
							<scroll-view scroll-y="true" style="max-height: 90vh;">

								<block v-for="(qitem, _index) of qList" :key="_index">
									  <form @submit="submit">

											<!-- 单选题 -->

											<view v-if="qitem.questionType == '0'">
												<view class='question naire' v-if='qitem.answer == null'>{{qitem.questionNo}}.{{qitem.questionName}}
														<view class="question-item">
														   <u-radio-group
															  placement="column"
															>
															  <u-radio
																:customStyle="{marginBottom: '8px'}"
																v-for="(sitem, i) of qitem.options"
																:key="i"
																:label="sitem.optionText"
																:name="sitem.optionText"
																@change="radioChange(qitem,sitem)"
																label-size="13px"
															  >
															  </u-radio>
															</u-radio-group>
														</view>
												</view>
												<view class='question naire' v-else>{{qitem.questionNo}}.{{qitem.questionName}}<text>(已答)</text>
														<view class="question-item">
														   <radio-group
															  placement="column"
															>
																<view class="radioItem">
																	  <radio
																		style="transform:scale(0.7)"
																		disabled
																		v-for="(sitem, i) of qitem.options"
																		:key="i"
																		label-size="13px"
																		:checked="sitem.optionText == qitem.answer"
																	  >{{sitem.optionText}}
																	  </radio>
																</view>
															</radio-group>
														</view>
												</view>
											</view>



											<!-- 多选题 -->
											<view v-if="qitem.questionType == '1'">
												<view class='question naire' v-if='qitem.answer == null'>{{qitem.questionNo}}.{{qitem.questionName}}<text class="textNum">(多选)</text>
												   <view class="question-item">
													   <checkbox-group @change="checkboxChange" :data-qitem="qitem" placement="column">
															<label class="" v-for="(mitem, i) of qitem.options" :key="i">
																<view class="checkItem">
																	<checkbox :value="[mitem.optionId,mitem.optionText]" :checked="item.checked" style="transform:scale(0.7)"/>{{mitem.optionText}}
																</view>
															</label>
														</checkbox-group>
													</view>
												</view>
												<view class='question naire' v-else>{{qitem.questionNo}}.{{qitem.questionName}}<text>(已答)</text>
												   <view class="question-item">
													   <checkbox-group :data-qitem="qitem" placement="column" disabled>
															<label class="" v-for="(mitem, i) of qitem.options" :key="i">
																<view class="checkItem">
																	<checkbox :value="[mitem.optionId,mitem.optionText]" style="transform:scale(0.7)" disabled :checked="mitem.checked"/>{{mitem.optionText}}
																</view>
															</label>
														</checkbox-group>
													</view>
												</view>
											</view>


											<!-- 填空题 -->
											<view v-if="qitem.questionType == '2'">
												<view class='question naire1' v-if='qitem.answer == null'>{{qitem.questionNo}}.{{qitem.questionName}}
													<view class="question-item">
													   <input
														  class="inputItem"
														  placeholder="请输入内容"
														  :data-qitem="qitem"
														  @blur="foucsChange"
														></input>
													</view>
												</view>
												<view class='question naire1' v-else >{{qitem.questionNo}}.{{qitem.questionName}}<text>(已答)</text>
													<view class="question-item">
													   <input
														  :value='qitem.answer'
														  class="inputItem"
														  placeholder="请输入内容"
														  :data-qitem="qitem"
														  disabled
														></input>
													</view>
												</view>
											</view>


											<!-- 问答题 -->
											<view v-if="qitem.questionType == '3'">
												<view class='question naire' v-if='qitem.answer == null'>{{qitem.questionNo}}.{{qitem.questionName}}
													<view class="question-item">
														<textarea class="textareaItem" :data-qitem="qitem"  placeholder="请输入内容" @blur="foucsChange1"></textarea>
													</view>
												</view>
												<view class='question naire' v-else>{{qitem.questionNo}}.{{qitem.questionName}}<text>(已答)</text>
													<view class="question-item">
														<textarea :value='qitem.answer' class="textareaItem" :data-qitem="qitem"  placeholder="请输入内容" disabled></textarea>
													</view>
												</view>
											</view>




											<view class='button-group' v-show="_index == qList.length-1">
											  <button class='button' hover-class='none' form-type='submit' @click='this.show1 = true'>保存</button>
											</view>

									  </form>

								</block>

								<view>
									<u-popup :show="show1" @close="this.show1 = false" closeable="true" closeIconPos="top-right" overlayOpacity='0.5'>
										<view class="textInPopup">
											<text>请您检查无误后确认提交保存！</text>
											<button class='buttonInPopup' @click='save'>确认保存</button>
										</view>
									</u-popup>
									<u-popup :show="show2" @close="this.show2 = false" closeable="true" closeIconPos="top-right" overlayOpacity='0.5'>
										<view class="textInPopup">
											<text>提交后不可修改，请您检查后确认是否提交！</text>
											<button class='buttonInPopup' @click='formSubmit' >确认提交</button>
										</view>
									</u-popup>
									<u-popup :show="show3" @close="this.show3 = false" closeable="true" closeIconPos="top-right" overlayOpacity='0.5'>
										<view class="textInPopup">
											<text>请确认所答题目已进行保存后再进行暂存！</text>
											<button class='buttonInPopup' @click='temSubmit' >确认暂存</button>
										</view>
									</u-popup>
								</view>

							</scroll-view>

						</view>
						<view class='container' v-else>
							<u-empty
								text="暂无题目数据"
								mode="data"
								icon="http://cdn.uviewui.com/uview/empty/data.png"
							>
							</u-empty>
						</view>
					</view>
				</block>

		    </view>
		  </view>

		</view>




	</view>
</template>

<script>
	// import {
	// 	getLabelBySurveyId,
	// 	qlistByLabelId,
	// 	collectAnswers,
	// 	collectTemAnswers,
	// 	listAnswer
	// } from '@/common/questionnaire.js'
	export default {
		data() {
			return {
				info:{},
				//问题列表
				qList: [],
				//单label答案暂存
				answer: [],
				//保存按钮点击后将answer放入这里，等待提交至后端
				mainAnswer:[],
				//label列表
				labelList:[],
				curLabelName:'',
				id: 0,
				active:0,
				currentTab:0,
				show1:false,
				show2:false,
				show3:false,
				notifyshow:false
			}
		},

		onLoad: function(option){ //option为object类型，会序列化上个页面传递的参数
			// console.log(option.item); //打印出上个页面传递的参数。
			// const details = JSON.parse(option.item);
			// console.log(details);
			// this.info = details;
			this.info.surveyId = option.id
			this.getLabelList(option.id);
			// this.getLabelList(6);

		},
		methods: {
			showToast() {
				const params = {type: 'loading',message: "正在加载"}
				this.$refs.uToast.show({
					...params
				})
			},
			showNotify(){
				this.$refs.uToastSuccess.show({
					type: 'success',
					title: '成功主题(带图标)',
					message: "提交成功，感谢您的回答",
					iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png'
				})
			},
			showNotifyBySave(){
				this.$refs.uToastSuccess.show({
					type: 'success',
					title: '成功主题(带图标)',
					message: "保存成功",
					iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png'
				})
			},

			//根据labelId查询问题信息
			getQListByLabelId(param){
				let riderInfo = uni.getStorageSync('riderInfo')
				const data = {
				  surveyId:this.info.surveyId,
				  labelId:this.labelList[this.active].id,
				  userId:riderInfo.ridersId
				  //userId:'8506546431086353623'
				}
				const questionList = [];
				console.log(456,data)
				console.log(45,param)

				this.$api.questionnaire.qlistByLabelId(param).then(res=>{
					console.log(6,res)
					for(let a in res.data){
						questionList.push(res.data[a])
					}
					// this.$api.questionnaire.listAnswer(data).then(response=>{
					// 	console.log("=======",response)
					// 	if(response.code === 200){
					// 		if(response.rows == null){
					// 			this.qList = questionList
					// 		}else{
					// 			//将问题数据和答案数据放在一起
					// 			console.log(123,response.rows)
					// 			const row = response.rows
					// 			for(let i in questionList){
					// 			  //判断多选题，处理答案
					// 			  if(questionList[i].questionType === '1'){
					// 				for(let j in row){
					// 				  if(questionList[i].questionId === row[j].questionId){
					// 					  //判断如果该选项是用户作答的答案，就增加一个属性checked为true，用于页面展示
					// 					  for(let o in questionList[i].options){
					// 						  if(questionList[i].options[o].optionId == row[j].optionId){
					// 							  questionList[i].options[o].checked = true
					// 							  break
					// 						  }
					// 					  }
					// 				  }
					// 				}
					// 			  }else{//其他题目答案处理
					// 				for(let j in row){
					// 				  if(questionList[i].questionId === row[j].questionId){
					// 					questionList[i].answerId = row[j].optionId
					// 					questionList[i].answer = row[j].extendValue
					// 				  }
					// 				}
					// 			  }

					// 			}
					// 			this.qList = questionList
					// 		}
					// 	}else{
					// 		this.qList = questionList
					// 	}
					// })
				})
			  },

			//根据问卷id查询label数据
			getLabelList(suveryId){
				// this.showToast()
				this.$api.questionnaire.getLabelBySurveyId(suveryId).then(res=>{
					uni.hideLoading();
					console.log(123,res)
					//在这里获取label信息并存入data中的label表中
					if(res.data[0].children == null){
						this.labelList.push(res.data[0])
					}else{
						this.labelList = res.data[0].children
					}
				})

				setTimeout(()=>{
					console.log(this.labelList)
				    this.curLabelName = this.labelList[0].label

					//根据label数量获取问卷数据直接存入qlist，qlist相当于二维数组
					this.getQListByLabelId(this.labelList[0].id)

				},200);

			},



			//单选框事件
			radioChange(qitem,sitem) {
				let flag = 0;
				for(var i in this.answer){
					//如果答案数组中已经包含该项，直接进行内容的修改
					if(qitem.questionId == this.answer[i].questionId){
						flag = 1;
						this.answer[i].optionId = sitem.optionId;
						this.answer[i].extendValue = sitem.optionText;
						break;
					}
				}
				//如果该项并未被包含在数组内，放进数组
				if(flag == 0){
					const a = {};
					a.surveyId = this.info.surveyId;
					a.labelId = this.labelList[this.active].id;
					a.questionId = qitem.questionId;
					a.optionId = sitem.optionId;
					a.extendValue = sitem.optionText;
					this.answer.push(a);
				}
				console.log(this.answer)
			},

			//多选题事件
			checkboxChange(e) {
			    console.log('change', e);
				let qitem = e.target.dataset.qitem
				const value = e.detail.value

				for(let i = 0;i<this.answer.length;i++){
					//如果答案数组中已经包含该项，直接进行删除
					if(qitem.questionId === this.answer[i].questionId){
						this.answer.splice(i, 1);
						i = i-1;
					}
				}

				if(value.length != 0){
					//遍历用户选择的结果数组，存进answer
					for(var v in value){
						const a = {};
						a.surveyId = this.info.surveyId;
						a.labelId = this.labelList[this.active].id;
						a.questionId = qitem.questionId;
						const arr = value[v].split(',')
						a.optionId =  parseInt(arr[0]);
						a.extendValue = arr[1];
						this.answer.push(a);
					}
				}


				console.log(this.answer)
			},

			//单选框失去焦点事件，获取数据
			foucsChange(e){
				console.log("单选框失去焦点",e)
				let flag = 0;
				let qitem = e.target.dataset.qitem
				let value = e.detail.value
				for(var i in this.answer){
					//如果答案数组中已经包含该项，直接进行内容的修改
					if(qitem.questionId == this.answer[i].questionId){
						flag = 1;
						//问答题没有选项
						this.answer[i].optionId = 0;
						this.answer[i].extendValue = value;
						break;
					}
				}
				//如果该项并未被包含在数组内，放进数组
				if(flag == 0){
					const a = {};
					a.surveyId = this.info.surveyId;
					a.labelId = this.labelList[this.active].id;
					a.questionId = qitem.questionId;
					a.optionId = 0;
					a.extendValue = value;
					this.answer.push(a);
				}
				console.log(this.answer)
			},

			//多行输入框失去焦点事件，获取数据
			foucsChange1(e){
				console.log("textArea失去焦点",e)
				let flag = 0;
				let qitem = e.target.dataset.qitem
				let value = e.detail.value
				for(var i in this.answer){
					//如果答案数组中已经包含该项，直接进行内容的修改
					if(qitem.questionId == this.answer[i].questionId){
						flag = 1;
						//问答题没有选项
						this.answer[i].optionId = 0;
						this.answer[i].extendValue = value;
						break;
					}
				}
				//如果该项并未被包含在数组内，放进数组
				if(flag == 0){
					const a = {};
					a.surveyId = this.info.surveyId;
					a.labelId = this.labelList[this.active].id;
					a.questionId = qitem.questionId;
					a.optionId = 0;
					a.extendValue = value;
					this.answer.push(a);
				}
				console.log(this.answer)
			},





			// 左侧点击事件
			switchNav: function (e) {
				//this.showToast()
			    var id = e.target.id;
				this.curLabelName = this.labelList[id].label
			    if (this.currentTab == id) {
			      return false;
			    } else {
			        this.currentTab=id
			    }
			    this.active = id
				if(this.mainAnswer[id] == null ){
					this.answer = []
				}else{
					this.answer = this.mainAnswer[id]
				}

				//切换label属性时使用labelId查询问题数据
				this.getQListByLabelId(this.labelList[id].id)

			},


			//保存
			save(){
				let flag = 1
				//判断该内容是否被重复保存
				for(let i in this.mainAnswer){
					if(this.mainAnswer[i][0].questionId == this.answer[0].questionId){
						this.mainAnswer[i] = this.answer
						flag = 0
					}
				}
				if(flag == 1){
					this.mainAnswer.push(this.answer)
				}
				this.showNotifyBySave();
				this.show1 = false
				console.log(this.mainAnswer)
			},

			// //暂存
			temSubmit(){
				let flag = 0;
				for(var i in this.mainAnswer){
					this.mainAnswer[i][0].userId = this.info.userId
					console.log(this.mainAnswer[i])
					this.$api.questionnaire.collectTemAnswers(this.mainAnswer[i]).then(res=>{
						console.log(res)
						//判断是否添加成功，添加成功flag+1
						if(res.code == 200){
							flag = flag+1
						}
					})
				}
				if( flag == this.mainAnswer.length){
					this.showNotify();
					setTimeout(()=>{
						wx.reLaunch({
							url: '/pages/enterprise/question/questionList'
						});
					},1000)
				}
			},

			//提交
			formSubmit: function(e) {
				this.show2 = false
				let flag = 0;
				for(var i in this.mainAnswer){
					this.mainAnswer[i][0].userId = this.info.userId
					console.log(this.mainAnswer[i])
					this.$api.questionnaire.collectAnswers(this.mainAnswer[i]).then(res=>{
						console.log(res)
						//判断是否添加成功，添加成功flag+1
						if(res.code == 200){
							flag = flag+1
						}
					})
				}
				if( flag == this.mainAnswer.length){
					this.showNotify();
					setTimeout(()=>{
						wx.reLaunch({
							url: '/pages/enterprise/question/questionList'
						});
					},1000)
				}
			},

			submit(e) {

			},
		}
	}
</script>

<style lang="scss">
/* miniprogram/pages/testSAS/testSAS.wxss */
#main{
	height: 100%;
}
//头部信息展示样式
.header{
	width: 100%;
	height: 180rpx;
	background-color: #38a9e1;
	color:white;
	.main_title{
		margin-left: 30rpx;
		padding-top: 20rpx;
		font-size: 30rpx;
		font-weight: 650;
	}
	.vice_title{
		margin-left: 30rpx;
	}
	.top-Button{
		width: 15%;
		height: 50rpx;
		margin-right: 20rpx;
		margin-top: -8rpx;
		font-size: 25rpx;
		float: right;
		box-shadow: black 1px;
		color: #38a9e1;
	}
	.header_footer text{
		margin-left: 30rpx;
		font-size: 25rpx;
	}
}



//左侧样式
.productNav{
   display: flex;
  // flex-direction: row;
  // font-family: "Microsoft YaHei"
  height: calc(100% - 150rpx);
}
.left{
  width: 25%;
  font-size: 25rpx;
  background-color: #f4f4f4;
}
.left view{
  text-align: center;
  height: 80rpx;
  line-height: 80rpx;
}
.selected{
  background-color: #fff;
  border-left: 2px solid #38a9e1;
  font-weight: bold;
  color: #38a9e1;
  overflow: hidden;
  text-overflow:ellipsis;
}
.normal{
  background-color: #f4f4f4;
  border-bottom: 1px solid #f2f2f2;
  overflow: hidden;
  text-overflow:ellipsis;
}

//右侧样式
.right{
  width:100%;
  //height: 100%;
  margin: 0;
  background-color: white;
  flex-direction: column;
  //height: calc(100vh - 90px);
  overflow-y: scroll;
  overflow-x: hidden;
  overflow: auto;
}
//主体答题样式
.container {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;//（决定元素排列方向）沿垂直主轴从上到下排列，起点在上沿
	justify-content: flex-start;//从行首起始位置开始排列
}
.naire {
  height: 240rpx;
}
.naire1 {
  height: 150rpx;
}
.question {
  font-size: 28rpx;
  margin-top: 20rpx;
  margin-left: 20rpx;
  color: #38a9e1;
}
.textNum{
	font-size: 25rpx;
	line-height:25rpx;
	color: #38a9e1;
}
.question text{
	font-size: 25rpx;
	line-height:25rpx;
	color: #2b74e1;
}
.question-item{
	margin-top: 20rpx;
}
.checkItem{
	margin-top: -13rpx;
	height: 12rpx;
	color: gray;
	font-size: 25rpx;
}
.inputItem{
	border-radius: 10rpx;
	border: 1px solid gray;
	height: 60rpx;
	min-height: 60rpx;
	line-height: 25rpx;
	width: 95%;
	color: gray;
}
.textareaItem{
	margin-top: -15rpx;
	border-radius: 10rpx;
	border: 1px solid gray;
	height: 180rpx;
	min-height: 180rpx;
	width: 95%;
	color: gray;
}

.border {
  height: 2rpx;
  width: 90%;
  background-color: #d4d4d4;
  margin: 16rpx auto;
}


.button-group {
  display: flex;
  flex-direction: row;
  width: 80%;
  margin: auto;
  margin-top: 20rpx;
  justify-content: space-between;
}
.button {
  background: #38a9e1;
  border-radius: 100rpx;
  font-size: 30rpx;
  line-height: 52rpx;
  height: 52rpx;
  width: 172rpx;
  margin-top: 10rpx;
  font-weight: bold;
  color: #fff;
}
.button::after {
  border: 0;
}
.id {
  text-align: center;
  font-size: 24rpx;
  color: #c2c2c2;
  margin: auto;
  margin-top: 20rpx;
}
.textInPopup{
	height: 300rpx;
}
.textInPopup text{
	margin-left: 9%;
	height: 200rpx;
	line-height: 200rpx;
	font-weight: 450;
	font-size: 33rpx;
	margin-bottom: -10rpx;
}
.buttonInPopup{
	background: #38a9e1;
	border-radius: 100rpx;
	font-size: 30rpx;
	line-height: 52rpx;
	height: 52rpx;
	width: 200rpx;
	font-weight: bold;
	color: #fff;
}

</style>
